package view;

import java.io.InputStream;
import java.util.Date;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import lib.BitmapButtonField;
import lib.EmbossedButtonField;
import lib.Util;
import lib.classes.HttpMultipartRequest;
import lib.classes.Profile;
import lib.classes.VerticalFieldManagerFieldSet;
import lib.gui.ScreenTemplate;
import model.DB;
import net.rim.blackberry.api.bbm.platform.profile.UserProfile;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.PNGEncodedImage;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.FocusChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.PasswordEditField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Border;
import net.rim.device.api.ui.decor.BorderFactory;

import com.samples.fileSelectorPopup.FileSelectorPopupScreen;

public class RegisterDevice extends ScreenTemplate implements FieldChangeListener, FocusChangeListener
{
	private CheckboxField cpyBBMSettings;
	UserProfile BBMprofile;
	AutoTextEditField screenName;
	AutoTextEditField status;
	AutoTextEditField aboutYou;
	ObjectChoiceField gender;
	DateField dob;
	AutoTextEditField city;
	AutoTextEditField province;
	AutoTextEditField country;
	CheckboxField searchable;
	EmbossedButtonField submit;
	BitmapButtonField profilePic;
	HorizontalFieldManager dpHF;
	AutoTextEditField email;
	PasswordEditField password;
	EmbossedButtonField nextPane;
	EncodedImage dp;
	VerticalFieldManagerFieldSet pane2;
	VerticalFieldManagerFieldSet pane1;
	VerticalFieldManager p2;
	VerticalFieldManager p1;
	VerticalFieldManager main;
	
	public RegisterDevice() 
	{
		super("Create Device's Profile", true);
		main = new VerticalFieldManager();
		p1 = new VerticalFieldManager(USE_ALL_WIDTH);
		p2 = new VerticalFieldManager(USE_ALL_WIDTH);
		
        pane1 = new VerticalFieldManagerFieldSet();
        email = new AutoTextEditField("Email as Username: ", "");
        password = new PasswordEditField("Password: ","");
        nextPane = new EmbossedButtonField("Next >>");
        nextPane.setPadding(5, 5, 5, 5);
		pane1.add(email);
		pane1.add(password);
		p1.add(pane1);
		HorizontalFieldManager h_next = new HorizontalFieldManager(USE_ALL_WIDTH | Field.FIELD_RIGHT);
		h_next.add(nextPane);
		p1.add(h_next);
		nextPane.setChangeListener(this);
		main.add(p1);
		
		
		pane2 = new VerticalFieldManagerFieldSet();
		if(ScreenTemplate.platformContext != null && ScreenTemplate.platformContext.isAccessAllowed())
		{
			BBMprofile = ScreenTemplate.platformContext.getUserProfile();
			cpyBBMSettings = new CheckboxField("Copy BBM Settings", true)
			{
				public void paint(Graphics g)
				{
					g.setColor(Color.WHITE);
					super.paint(g);
				}
			};
	        
	        dp = PNGEncodedImage.encode(BBMprofile.getDisplayPicture());
	        EncodedImage _ei = Util.scaleImageToWidth(dp, 96);
	        _ei = Util.scaleImageToHeight(_ei, 96);
	        
	        profilePic = new BitmapButtonField(_ei.getBitmap());
	        profilePic.setChangeListener(this);
	        profilePic.setFocusListener(this);
	        profilePic.setBorder(BorderFactory.createRoundedBorder(new XYEdges(2,2,2,2)));
	        
	        String statusmsg =  BBMprofile.getPersonalMessage().trim().equals("")? BBMprofile.getStatusMessage(): BBMprofile.getPersonalMessage();
	        screenName = new AutoTextEditField("Screen Name: ", BBMprofile.getDisplayName(), 70,EditField.FILTER_DEFAULT);
	        status = new AutoTextEditField("Watchu up to: ", statusmsg, 1024, EditField.FILTER_DEFAULT);
	        aboutYou = new AutoTextEditField("About you: ", "", 140, EditField.FILTER_DEFAULT);
	        gender = new ObjectChoiceField("Gender: ", new Object[]{"Male","Female"});
	        java.util.Date today = new java.util.Date();
	        dob = new DateField("Date Of Birth: ", today.getTime(),DateField.DATE | DrawStyle.LEFT);
	        city = new AutoTextEditField("City: ", "", 60, EditField.FILTER_DEFAULT);
	        province = new AutoTextEditField("Province: ", "", 60, EditField.FILTER_DEFAULT);
	        country = new AutoTextEditField("Country: ", BBMprofile.getProfileLocation().getCountryCode());
	        country.setEditable(false);
	        searchable = new CheckboxField(" Profile Searchable?", true);
	        dpHF = new HorizontalFieldManager(Field.USE_ALL_WIDTH | Field.FIELD_HCENTER | DrawStyle.HCENTER );
	        dpHF.add(profilePic);
	        dpHF.setPadding(new XYEdges(5,5,5,5));
	        p2.add(dpHF);
	        p2.add(cpyBBMSettings);
		}else
		{
			//cpyBBMSettings = new CheckboxField("Copy BBM Settings", false);
	        
	        dp = EncodedImage.getEncodedImageResource("img/nopic.jpg");
	        EncodedImage _ei = Util.scaleImageToWidth(dp, 96);
	        _ei = Util.scaleImageToHeight(_ei, 96);
	        
	        profilePic = new BitmapButtonField(_ei.getBitmap());
	        profilePic.setChangeListener(this);
	        profilePic.setFocusListener(this);
	        profilePic.setBorder(BorderFactory.createRoundedBorder(new XYEdges(2,2,2,2)));
	        
	        String statusmsg =  "Testing";
	        screenName = new AutoTextEditField("Screen Name: ", "LegacyUntold", 70,EditField.FILTER_DEFAULT);
	        status = new AutoTextEditField("Watchu up to: ", statusmsg, 1024, EditField.FILTER_DEFAULT);
	        aboutYou = new AutoTextEditField("About you: ", "testing", 140, EditField.FILTER_DEFAULT);
	        gender = new ObjectChoiceField("Gender: ", new Object[]{"Male","Female"});
	        java.util.Date today = new java.util.Date();
	        dob = new DateField("Date Of Birth: ", today.getTime(),DateField.DATE | DrawStyle.LEFT);
	        city = new AutoTextEditField("City: ", "Richmond Hill", 60, EditField.FILTER_DEFAULT);
	        province = new AutoTextEditField("Province: ", "Toronto", 60, EditField.FILTER_DEFAULT);
	        country = new AutoTextEditField("Country: ", RadioInfo.getNetworkCountryCode(RadioInfo.getCurrentNetworkIndex()));
	        searchable = new CheckboxField(" Profile Searchable?", true);
	        
	        dpHF = new HorizontalFieldManager(Field.USE_ALL_WIDTH | Field.FIELD_HCENTER | DrawStyle.HCENTER);
	        dpHF.add(profilePic);
	        dpHF.setPadding(new XYEdges(5,5,5,5));
	        p2.add(dpHF);
		}
		       
        
        HorizontalFieldManager submitHF = new HorizontalFieldManager(Field.USE_ALL_WIDTH | Field.FIELD_HCENTER);
        submit = new EmbossedButtonField(" Submit ");
        submit.setChangeListener(this);

        EmbossedButtonField prev = new EmbossedButtonField("<< Previous");
        prev.setChangeListener(new FieldChangeListener() {
			
			public void fieldChanged(Field field, int context) 
			{
				main.deleteAll();
				main.add(p1);
				main.invalidate();
				invalidate();
			}
		});
        submitHF.add(prev);
        submitHF.setPadding(new XYEdges(5,5,5,5));
        submitHF.add(submit);
        
        
        screenName.setPadding(3, 3, 3, 3);
        pane2.add(screenName);pane2.add(new SeparatorField());
        status.setPadding(3, 3, 3, 3);
        pane2.add(status); pane2.add(new SeparatorField());
        aboutYou.setPadding(3, 3, 3, 3);
        pane2.add(aboutYou);pane2.add(new SeparatorField());
        dob.setPadding(3, 3, 3, 3);
        pane2.add(dob); pane2.add(new SeparatorField());
        gender.setPadding(3, 3, 3, 3);
        pane2.add(gender);pane2.add(new SeparatorField());
        city.setPadding(3, 3, 3, 3);
        pane2.add(city); pane2.add(new SeparatorField());
        province.setPadding(3, 3, 3, 3);
        pane2.add(province); pane2.add(new SeparatorField());
        country.setPadding(3, 3, 3, 3);
        pane2.add(country);
        p2.add(pane2);
        p2.add(submitHF);
        
        //main.add(p1);
        add(main);
        
	}

	public void fieldChanged(Field field, int arg1) 
	{
		if(field == nextPane)
		{
			if(isValidForm())
			{
				if(!Util.emailExists(email.getText()))
				{
					main.deleteAll();
					main.add(p2);
					main.invalidate();
					invalidate();
				}else
				{
					UiApplication.getUiApplication().invokeLater(new Runnable()
		            {
		                public void run()
		                {
		                    Dialog.alert("That email already exists in our system");
		                    //System.exit(0);            
		                } 
		            }); 
				}
			}
		}else if(field == cpyBBMSettings)
		{
			if(cpyBBMSettings.getChecked() && BBMprofile != null)
			{
				String statusmsg =  BBMprofile.getPersonalMessage().trim().equals("")? BBMprofile.getStatusMessage(): BBMprofile.getPersonalMessage();
				screenName.setText(BBMprofile.getDisplayName());
				status.setText(statusmsg);
			}
		}else if(field == submit)
		{
			if(verifySubmit())
			{
				System.out.println("After Verify Submit");
		            try
		            {
		            	/*httpConn = (HttpConnection)Connector.open(Util.Host(DB.serverURL, -1), Connector.READ_WRITE);
		            	*/boolean bbmsync = false;
		            	if(cpyBBMSettings != null)
		            	{
		            		bbmsync = cpyBBMSettings.getChecked();
		            	}
		            	System.out.println("DBUG::>> Before profile create");
		            	Profile p = new Profile(DeviceInfo.getDeviceId(), new Date(dob.getDate()), screenName.getText(), status.getText(), aboutYou.getText(), 
		            			gender.getChoice(gender.getSelectedIndex())+"", city.getText(), province.getText(), country.getText(), bbmsync);
		            	p.setImage(dp);
		            	p.setEmail(this.email.getText().toLowerCase());
		            	p.setPass(this.password.getText());
		            	p.setPrivate(searchable.getChecked()? false:true);
		            	
		            	System.out.println("DBUG::>> After profile create");
		            	
		            	Hashtable params = p.getHashtableData();
		            	params.put("action", "register");
		    			
		            	byte[] fileBytes = p.getImage().getData(); //retrieve file bytes with your own code
		    			HttpMultipartRequest req = new HttpMultipartRequest(
		    					Util.Host(DB.serverURL, -1), params, "upload_dp", p.getPin()+"_dp.png", "image/png", fileBytes );
		    			System.out.println("DBUG::>> After HttpMultiRequest");
		    			byte[] response = req.send();
		    			String s = new String(response);
		    			System.out.println("CONTENTS OF DATA RECEIVED::\n"+s);
		                if(s.length() > 5 && s.toLowerCase().indexOf("success") > 0)
		                {
			    			ScreenTemplate.initDB();
				            _db.insertProfileIntoDB(p);
				            Dialog.inform("You've successfully registered your device, Happy Mingling :)");
				            ScreenTemplate.profile = p;
				            touchRegistrationFlag();
				            switchScreen(new Home());
		                }
		            }
		            catch (Exception e)
		            {
		                System.err.println("Caught IOException: " + e.getMessage() + " :: " + e.toString());
		            }
		       // }
			}else
			{
				Dialog.alert("You must fill out all fields");
			}
			
		}else if(field == profilePic)
		{
			String imageExtensions[] = {"jpg", "jpeg", "bmp", "png", "gif"};

               FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
               fps.pickFile();
               String theFile = "file:///"+fps.getFile();
               System.out.println("FILE PICKED= "+theFile);
               if(theFile != null)
               {
            	   try{
	            	   FileConnection fcon = (FileConnection) Connector.open(theFile );
	            	   System.out.println("FILE PICKED= "+theFile + " File Exists="+fcon.exists());
	            	   if(fcon.exists()) 
	            	   {
	                       byte[] content = new byte[(int) fcon.fileSize()];
	                         int readOffset = 0;
	                         int readBytes = 0;
	                         int bytesToRead = content.length - readOffset;
	                         InputStream is = fcon.openInputStream();
	                         while (bytesToRead > 0) {
	                           readBytes = is.read(content, readOffset, bytesToRead);
	                           if (readBytes < 0) {
	                             break;
	                           }
	                           readOffset += readBytes;
	                           bytesToRead -= readBytes;
	                         }
	                         is.close();
	                       EncodedImage image = EncodedImage.createEncodedImage(content,0,content.length);
	                       dp = image;
		            	   EncodedImage _ei = Util.scaleImageToWidth(dp, 96);
		                   _ei = Util.scaleImageToHeight(_ei, 96);
		                   dpHF.delete(profilePic);
		                   profilePic = new BitmapButtonField(_ei.getBitmap());
		                   profilePic.setChangeListener(this);
		                   dpHF.add(profilePic);
		                   dpHF.invalidate();
		                   this.invalidate();
		                   getContainer().invalidate();
	                   }
	            	}catch(Exception e)
            	   {
            		   System.out.println(e.getMessage());
            	   }
               }
		}
	}
	
	public boolean verifySubmit()
	{
		boolean submit = true;
		if(screenName.getText().trim().equals("")
			|| status.getText().trim().equals("")
			|| aboutYou.getText().trim().equals("")
			|| city.getText().trim().equals("")
			|| province.getText().trim().equals("")
			|| email.getText().trim().equals(""))
		{
			submit = false;
		}
		
		return submit;
	}

	public void uploadImage(String pin, EncodedImage image, String url)
	{
		try{

			byte[] fileBytes = image.getData(); //retrieve file bytes with your own code
			 
			Hashtable params = new Hashtable();
			params.put("pin", pin);
			//params.put("custom_param2", "param_value2");
			 
			HttpMultipartRequest req = new HttpMultipartRequest(
				url, params, "upload_dp", pin+"_dp.png", "image/png", fileBytes );
			 
			byte[] response = req.send();

		}catch (Exception e) {
			    // TODO: handle exception
			}
	}
	
	private boolean touchRegistrationFlag()
	{
		FileConnection fcon = null;
		boolean isRegistered = false;
		try{
			fcon = (FileConnection) Connector.open(Util.APPPATH+ Util.regFile, Connector.READ_WRITE );
			if(!fcon.exists())
				fcon.create();			
		}catch(Exception e)
		{
			System.out.println("isRegistered:: Error opening file");
		}
		return isRegistered;
	}

	public void focusChanged(Field field, int eventType) 
	{
		if(field == profilePic)
		{
			if(profilePic.isFocus())
			{
				profilePic.setBorder(BorderFactory.createRoundedBorder(new XYEdges(2,2,2,2), Color.BLUE, Border.STYLE_SOLID));
			}else
			{
				profilePic.setBorder(BorderFactory.createRoundedBorder(new XYEdges(2,2,2,2)));
			}
		}
	}
	
	private boolean isValidForm() 
	{
		return email.getText().trim().length() > 0 && password.getText().trim().length()>0;
	}
}
